package sale.wxb.loveshopping.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import sale.wxb.loveshopping.constant.FolderConst;
import sale.wxb.loveshopping.entity.common.ResultException;
import sale.wxb.loveshopping.dao.RelationResourceDao;
import sale.wxb.loveshopping.entity.model.RelationResource;
import sale.wxb.loveshopping.entity.yml.YmlConfigResource;
import sale.wxb.loveshopping.enums.ResponseEnum;
import sale.wxb.loveshopping.service.IRelationResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 文件资源关系表 服务实现类
 * </p>
 *
 * @author 王小宝
 * @since 2022-12-26
 */
@Transactional
@Service
@Slf4j
public class RelationResourceServiceImpl extends ServiceImpl<RelationResourceDao, RelationResource> implements IRelationResourceService {
    @Autowired
    private YmlConfigResource ymlConfigResource;

    private String getFolder(String type) {
        String s = "";
        if (type.contains("video")) {
            // 视频
            s = FolderConst.VIDEO;
        } else if (type.contains("audio")) {
            // 音频
            s = FolderConst.AUDIO;
        } else if (type.contains("image")) {
            // 图片
            s = FolderConst.IMAGE;
        } else if (type.contains("application")) {
            // 表格
            s = FolderConst.OFFICE;
        } else {
            // 其他
            s = FolderConst.OTHER;
        }
        return s;
    }

    /**
     * 保存文件到本地
     */
    private Map<String, Object> saveFile(MultipartFile multipartFile) throws IOException {

        if (multipartFile == null) {
            throw new ResultException("文件不能为空");
        }

        String dateformat = DateUtil.format(DateUtil.date(), "yyyyMMdd");
        String originalFilename = multipartFile.getOriginalFilename();
        String path = getFolder(Objects.requireNonNull(multipartFile.getContentType())) + "/" + dateformat;
        String folderPath = ymlConfigResource.getFileSavePath() + "/" + path;
        File folder = new File(folderPath);

        // 创建目录
        if (!folder.exists()) {
            boolean mkdirs = folder.mkdirs();

            if (!mkdirs) {
                throw new ResultException(ResponseEnum.SERVER_ERROR, "创建文件目录失败,请联系管理员检查目录权限");
            }
        }

        // 文件名
        String filename = IdUtil.simpleUUID() + "." + FileNameUtil.extName(originalFilename);
        // 移动文件到该目录
        File file = new File(folderPath, filename);
        multipartFile.transferTo(file);
        Map<String, Object> map = new HashMap<>();
        map.put("file", file);
        map.put("path", path);
        return map;
    }

    /**
     * 文件上传
     * @return List<RelationResource>
     */
    private List<RelationResource> fileUpload(List<MultipartFile> multipartFiles) {
        List<RelationResource> RelationResources = new ArrayList<>();
        multipartFiles.forEach(x -> {
            File file;
            String path = "";
            try {
                Map<String, Object> map = saveFile(x);
                file = (File) map.get("file");
                path = (String) map.get("path");
            } catch (IOException e) {
                log.error(e.getMessage());
                throw new RuntimeException("保存文件失败");
            }

            RelationResource RelationResource = new RelationResource();
            RelationResource.setFilename(file.getName());
            RelationResource.setPath(ymlConfigResource.getPathPrefix() + "/" + path + "/" + file.getName());
            RelationResource.setOriginalFilename(x.getOriginalFilename());
            RelationResource.setDiskPath(file.getAbsolutePath());
            RelationResource.setSuffix(FileNameUtil.extName(file.getName()));
            RelationResource.setFilesize(x.getSize());
            RelationResource.setSystemClear(0);
            RelationResources.add(RelationResource);
        });
        if (!this.saveBatch(RelationResources)) {
            // TODO 删除掉失败的文件
            throw new ResultException("写入数据库失败!");
        };
        return RelationResources;
    }

    @Override
    public RelationResource singleFileUpload(MultipartFile file) {
        List<RelationResource> RelationResources = fileUpload(Collections.singletonList(file));
        return RelationResources.stream().findFirst().orElse(null);
    }

    @Override
    public List<RelationResource> multipleFileUpload(List<MultipartFile> files) {
        return fileUpload(files);
    }

    @Override
    public void removeFilesByRelationId(List<Long> relationId) {

    }

    @Override
    public Boolean setRelationResourceId(Long resourceId, Long relationId) {
        RelationResource RelationResource = this.getById(resourceId);
        if (ObjectUtils.isEmpty(RelationResource)) {
            throw new ResultException("资源不存在");
        }
        RelationResource.setRelationId(relationId);
        return this.saveOrUpdate(RelationResource);
    }
}
